<template>
  <div class="app-container">
    <el-card class="picture-component" style="margin-left:8px;">
      <div class="post">
        <div class="user-image">
          <el-carousel :interval="6000" type="card" height="240px">
            <el-carousel-item v-for="item in carouselImages" :key="item">
              <img :src="item" class="image">
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </el-card>

    <div class="filter-container">
      <el-input v-model="queryname" placeholder="number" style="margin-top: 30px;width: 200px;" class="filter-item" />
      <!-- <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
          <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select> -->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      style="margin-top: 20px;"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="ID" width="50" align="center">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="Number" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Ship From" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.ship_from }}
        </template>
      </el-table-column>
      <el-table-column label="Ship To" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.ship_to }}
        </template>
      </el-table-column>
      <el-table-column label="Type" width="60" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column label="Weight" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.weight }}
        </template>
      </el-table-column>
      <el-table-column label="Description" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.des }}
        </template>
      </el-table-column>
      <el-table-column label="Status" width="150px" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.state | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" >
            Edit
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="Number" prop="num">
          <el-input v-model="temp.num" />
        </el-form-item>
        <el-form-item label="Ship From" prop="ship_from">
          <el-input v-model="temp.ship_from" />
        </el-form-item>
        <el-form-item label="Ship To" prop="ship_to">
          <el-input v-model="temp.ship_to" />
        </el-form-item>
        <el-form-item label="Type">
          <el-select v-model="temp.type" prop="type">
            <el-option label="Box" value="box" />
            <el-option label="Bag" value="bag" />
          </el-select>
        </el-form-item>
        <el-form-item label="Weight" prop="weight">
          <el-input v-model="temp.weight" />
        </el-form-item>
        <el-form-item label="Description" prop="des">
          <el-input v-model="temp.des" />
        </el-form-item>
        <el-form-item label="Status">
          <el-select v-model="temp.state">
            <el-option label="In Transit" value="0" />
            <el-option label="Finished" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, register, update, deleteById } from '@/api/transportation'
import img1 from './image/1.png'
import img2 from './image/2.png'
import img3 from './image/3.png'

const calendarTypeOptions = [
  { key: '0', display_name: 'In Transit' },
  { key: '1', display_name: 'Finished' }
]

// eslint-disable-next-line no-unused-vars
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      queryname: '',
      temp: {
        id: undefined,
        num: '',
        ship_from: '',
        ship_to: '',
        type: '',
        weight: '',
        des: '',
        state: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      carouselImages: [
        img1, img2, img3
      ]
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      // this.listLoading = true
      getList({}).then(response => {
        this.list = response.data.list
        this.listLoading = false
      }).catch(error => {
        console.log(error)
      })
    },
    handleFilter() {
      console.log(this.queryname)
      getList({
        'num': this.queryname
      }).then(response => {
        console.log(response)
        this.list = response.data.list
        this.listLoading = false
      }).catch(error => {
        console.log(error)
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        from: '',
        to: '',
        type: '',
        weight: '',
        des: '',
        status: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          register(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      console.log(row.id)
      const formdata = new FormData()
      formdata.append('id', row.id)
      console.log(formdata)
      deleteById(formdata).then(() => {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
      }).catch(error => {
        console.log(error)
      })
      this.list.splice(index, 1)
    }
  }
}
</script>

